package cn.topevery.garden.dal.dao.impl;

import cn.topevery.garden.dal.dao.GreFileDao;
import cn.topevery.garden.dal.dao.ProjectManagementDao;
import cn.topevery.garden.entity.dto.ProjectManagementDTO;
import cn.topevery.garden.entity.po.ProjectManagement;
import cn.topevery.garden.entity.query.ProjectManagementQuery;
import cn.topevery.garden.entity.vo.ProjectManagementVO;
import cn.topevery.garden.framework.base.BaseDaoImpl;
import hw.topevery.framework.db.CommandType;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.db.entity.SqlQueryMate;
import hw.topevery.framework.db.entity.SqlUpdateMate;
import hw.topevery.framework.db.enums.ScriptConditionEnum;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.entity.KeyValue;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 项目管理信息表
 *
 * @author code-generate
 * @date 2022-02-15
 */
@Repository
public class ProjectManagementDaoImpl extends BaseDaoImpl<ProjectManagement> implements ProjectManagementDao {
    @Override
    public <P extends DbCsp> List<ProjectManagement> getSearch(P para) {
        return null;
    }

    @Autowired
    GreFileDao greFileDao;

    @Override
    public DataPager<ProjectManagementVO> listPage(ProjectManagementQuery query) {
        String table = "t_project_management tpm";

        String columns = "tpm.*";

        int pageIndex = query.pageIndex - 1;
        int pageSize = query.pageSize;

        SqlQueryMate sqlQueryMate = new SqlQueryMate(table).setColumns(columns).setOrderBy("tpm.c_id desc");
        sqlQueryMate
                .where(true, "tpm.c_db_status", ScriptConditionEnum.Eq, 0)
                .where(query.getProjectStatus()!=null, "tpm.c_project_status", ScriptConditionEnum.Eq, query.getProjectStatus())
                .where(query.getProjectType()!=null, "tpm.c_project_type", ScriptConditionEnum.Eq, query.getProjectType())
                .where(StringUtils.isNotBlank(query.getProjectCode()), "tpm.c_project_code", ScriptConditionEnum.Like, query.getProjectCode())
                .where(StringUtils.isNotBlank(query.getName()), "tpm.c_name", ScriptConditionEnum.Like, query.getTypeName())
                .where(StringUtils.isNotBlank(query.getPartyA()), "tpm.c_party_a", ScriptConditionEnum.Eq, query.getPartyA())
                .where(StringUtils.isNotBlank(query.getPartyB()), "tpm.c_party_b", ScriptConditionEnum.Eq, query.getPartyB())
                .where(StringUtils.isNotBlank(query.getPartyC()), "tpm.c_party_c", ScriptConditionEnum.Eq, query.getPartyC())
                .where(StringUtils.isNotBlank(query.getStartDate()), "tpm.c_start_date", ScriptConditionEnum.GreaterThanEq, query.getStartDate())
                .where(StringUtils.isNotBlank(query.getEndDate()), "tpm.c_end_date", ScriptConditionEnum.LessThanEq, query.getEndDate())
        ;

        return getDataPager(sqlQueryMate, pageSize, pageIndex, ProjectManagementVO.class);
    }

    @Override
    public ProjectManagement getEntityByColumn(String key,String value){
        KeyValue<String> map=new KeyValue<>();
        map.key=key;
        map.value=value;
        return getEntityByColumnEqValue(map);
    }

    @Override
    public void commit(String userId, ProjectManagementDTO dto) {
        boolean isUpdate = dto.getId() != null;
        LocalDateTime now = LocalDateTime.now();
        ProjectManagement projectManagement = new ProjectManagement();
        BeanUtils.copyProperties(dto, projectManagement);

        if (!isUpdate) {
            projectManagement.setDbStatus(true);
            projectManagement.setCreateId(userId);
            projectManagement.setCreateTime(now);
            projectManagement.setProjectCode(UUID.randomUUID().toString());
            saveOrUpdate(userId, projectManagement);
        } else {
            //如果是修改，先删除旧的附件，再把新的附件保存
            greFileDao.deleteByMainId(dto.getId(), userId, 1);
            projectManagement.setCreateTime(now);
            projectManagement.setCreateId(userId);
            saveOrUpdate(userId, projectManagement);
        }
    }

    @Override
    public void deleteBatchById(String userId, Integer[] ids) {
        SqlUpdateMate sqlUpdateMate = new SqlUpdateMate("t_project_management tpm");
        sqlUpdateMate.setColumnValue(true, "c_db_status", 1)
                .setColumnValue(true, "c_db_last_update_date", LocalDateTime.now())
                .setColumnValue(true, "c_db_last_update_id", Integer.valueOf(userId))
                .where(true, "c_id", ScriptConditionEnum.In, ids);
        run(sqlUpdateMate.getSql(), CommandType.Text, dbCommand -> {
            sqlUpdateMate.getParameters().forEach(dbCommand::addParameter);
            dbCommand.executeNonQuery();
        });
    }

    @Override
    public List<Map<String, Object>> getProjectNameList() {
        SqlQueryMate sqlQueryMate = new SqlQueryMate("t_project_management tpm")
                .setColumns("tpm.c_id id, tpm.c_name name");
        return getMap(sqlQueryMate);
    }

    @Override
    public void updateMapRange(Integer id, Float lat, Float lng) {
        String sql = "update t_project_management\n" +
                "set c_map_ranges=ST_GeomFromText('point( "+ lat + " " + lng + " )',4326)\n" +
                "where c_id=" + id;
        run(sql, CommandType.Text, dbCommand -> {
            dbCommand.executeNonQuery();
        });
    }

}
